//
//  AddressEditViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/4.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "AddressEditViewController.h"
#import "PcaModel.h"
#import "ASBirthSelectSheet.h"
#import "ShopcartOrderViewController.h"

@interface AddressEditViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet SZTextView *addressTextView;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (weak, nonatomic) IBOutlet UIButton *defaultButton;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;

@property (nonatomic, strong) NSMutableArray *pcaArray;
@property (nonatomic, copy) NSString *aid;
@end

@implementation AddressEditViewController
#pragma mark - Get
- (NSMutableArray *)pcaArray {
    if (!_pcaArray) {
        _pcaArray = [[NSMutableArray alloc] init];
    }
    return _pcaArray;
}
#pragma mark - IBAction
- (IBAction)chooseAddressButtonAction:(id)sender {
    [self.view endEditing:YES];
    [self getPcaData];
}
- (IBAction)defaultButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    
}
- (IBAction)saveButtonAction:(id)sender {
    
    if (!TextIsNotNil(self.nameTextField.text)) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请输入收货人姓名" animated:YES];
        return;
    }
    if (!TextIsNotNil(self.phoneTextField.text)) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请输入联系电话" animated:YES];
        return;
    }
    if (!TextIsNotNil(self.aid)) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请选择所在区域" animated:YES];
        return;
    }
    if (!TextIsNotNil(self.addressTextView.text)) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请输入详细地址" animated:YES];
        return;
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.nameTextField.text forKey:@"daname"];
    [dic setObject:self.phoneTextField.text forKey:@"datel"];
    [dic setObject:self.aid forKey:@"aid"];
    [dic setObject:self.addressTextView.text forKey:@"daaddress"];
    [dic setObject:[NSString stringWithFormat:@"%d",self.defaultButton.selected] forKey:@"isdefault"];
    if (self.type == AddressTypeEdit) {
        [dic setObject:self.editModel.daid forKey:@"daid"];
    }
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_Address parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"保存成功" animated:YES];
            if (self.type == AddressTypeShopcartNew) {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[ShopcartOrderViewController class]]) {
                        ((ShopcartOrderViewController *)controller).selectModel = [AddressModel mj_objectWithKeyValues:responseObject[@"data"]];
                        [self.navigationController popToViewController:controller animated:YES];
                        break;
                    }
                }
            } else {
                [self disMissSelf];
            }
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"200"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - action
- (void)getPcaData {
    if (self.pcaArray.count > 0) {
        // 直接显示
        [self showPcaPicker];
        return;
    }
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Pca parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self.pcaArray removeAllObjects];
            NSArray *array = responseObject[@"data"];
            for (NSDictionary *dic in array) {
                PcaModel *model = [PcaModel mj_objectWithKeyValues:dic];
                [self.pcaArray addObject:model];
            }
            // 显示地区选择的picker
            [self showPcaPicker];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)showPcaPicker {
    UIWindow *windowKey = [UIApplication sharedApplication].keyWindow;
    
    ASBirthSelectSheet *datesheet = [[ASBirthSelectSheet alloc] initWithFrame:windowKey.bounds type:sheetTypePca];
    datesheet.pcaArray = self.pcaArray;
    datesheet.GetSelectDate = ^(NSString *dateStr, NSString *addressStr) {
        // 修改地区接口
        NSLog(@"选择的区ID %@",dateStr);
        self.aid = dateStr;
        [self.areaLabel setText:addressStr];
    };
    
    [windowKey addSubview:datesheet];
    [datesheet showPickerView];
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:self.nameTextField];
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    //[self.sureButton setGradientHorizontal:nil];
}
- (void)createUI {
    
    [self hiddenShadowImage:NO];
    [self.addressTextView setTextContainerInset:UIEdgeInsetsMake(14, -6, 10, -6)];
    
    switch (self.type) {
        case AddressTypeNew: case AddressTypeShopcartNew:
        {
            self.title = @"添加新地址";
            NSString *address = [NSString stringWithFormat:@"%@%@%@",[UserInfo shareInstance].user.pname,[UserInfo shareInstance].user.cname,[UserInfo shareInstance].user.aname];
            if (TextIsNotNil(address)) {
                [self.areaLabel setText:address];
            } else {
                [self.areaLabel setText:@""];
            }
            
            NSString *addressID;
            if (TextIsNotNil([UserInfo shareInstance].user.aid)) {
                addressID = [UserInfo shareInstance].user.aid;
            } else if (TextIsNotNil([UserInfo shareInstance].user.cid)) {
                addressID = [UserInfo shareInstance].user.cid;
            } else if (TextIsNotNil([UserInfo shareInstance].user.pid)) {
                addressID = [UserInfo shareInstance].user.pid;
            }
            self.aid = addressID;
            break;
        }
        case AddressTypeEdit:
        {
            self.title = @"编辑地址";
            [self.nameTextField setText:self.editModel.daname];
            [self.phoneTextField setText:self.editModel.datel];
            [self.areaLabel setText:[NSString stringWithFormat:@"%@%@%@",self.editModel.pname,self.editModel.cname,self.editModel.aname]];
            [self.addressTextView setText:self.editModel.daaddress];
            [self.defaultButton setSelected:self.editModel.isdefault];
            
            self.aid = self.editModel.aid;
            break;
        }
        default:
            break;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.phoneTextField) {
        if ([string isEqualToString:@""]) {
            return YES;
        }
        // 手机号
        if (textField.text.length >= 11) {
            return NO;
        } else {
            return YES;
        }
    }
    return YES;
}

#define kMaxLength 8
-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    if (textField != self.nameTextField) {
        return;
    }
    NSString *toBeString = textField.text;
    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage; // 键盘输入模式
    if ([lang hasPrefix:@"zh-Han"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > kMaxLength) {
            textField.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:self.nameTextField];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
